package cn.iocoder.yudao.module.scrm.controller.admin.order;

import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.scrm.annotations.FieldCompareValidator;
import cn.iocoder.yudao.module.scrm.annotations.FieldCompareValidators;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.invoice.InvoiceDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.receivable.ReceivableDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.refund.RefundDO;
import cn.iocoder.yudao.module.scrm.dal.mysql.invoice.InvoiceMapper;
import cn.iocoder.yudao.module.scrm.dal.mysql.receivable.ReceivableMapper;
import cn.iocoder.yudao.module.scrm.dal.mysql.refund.RefundMapper;
import cn.iocoder.yudao.module.scrm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.scrm.enums.util.FieldNameType;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.*;

import cn.iocoder.yudao.module.scrm.controller.admin.order.vo.*;
import cn.iocoder.yudao.module.scrm.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.scrm.service.order.OrderService;

@Tag(name = "管理后台 - 订单")
@RestController
@RequestMapping("/scrm/order")
@Validated
public class OrderController {

    @Resource
    private OrderService orderService;
    @Resource
    private PermissionApi permissionApi;


    @PostMapping("/create")
    @Operation(summary = "创建订单")
    @PreAuthorize("@ss.hasPermission('scrm:order:create')")
    public CommonResult<Integer> createOrder(@Valid @RequestBody OrderSaveReqVO createReqVO,@RequestHeader("Tenant-Id") String tenantId) {
        return success(orderService.createOrder(createReqVO,tenantId));
    }

    @PutMapping("/update")
    @Operation(summary = "更新订单")
    @PreAuthorize("@ss.hasPermission('scrm:order:update')")
    @FieldCompareValidators( foreignKeyType = CrmBizTypeEnum.CRM_ORDER,foreignKeyFieldName = FieldNameType.SCRM_ORDER_TOTAL_MONEY,fieldCompareValidator = {
            @FieldCompareValidator(majorJeyType = CrmBizTypeEnum.CRM_RECEIVABLE,majorJeyFieldName = FieldNameType.SCRM_ORDER_TOTAL_MONEY,message = "金额限制"),
            @FieldCompareValidator(majorJeyType = CrmBizTypeEnum.CRM_REFUND,majorJeyFieldName = FieldNameType.SCRM_ORDER_TOTAL_MONEY,message = "金额限制"),
            @FieldCompareValidator(majorJeyType = CrmBizTypeEnum.CRM_INVOICE,majorJeyFieldName = FieldNameType.SCRM_ORDER_TOTAL_MONEY,message = "金额限制")
    })
    public CommonResult<Boolean> updateOrder(@Valid @RequestBody OrderSaveReqVO updateReqVO,@RequestHeader("Tenant-Id") String tenantId) {
        orderService.updateOrder(updateReqVO,  tenantId);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除订单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('scrm:order:delete')")
    public CommonResult<Boolean> deleteOrder(@RequestParam("id") Integer id) {
        orderService.deleteOrder(id);
        return success(true);
    }



    @GetMapping("/get")
    @Operation(summary = "获得订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('scrm:order:query')")
    public CommonResult<OrderRespVO> getOrder(@RequestParam("id") Integer id,@RequestHeader(value = "Tenant-Id") String tenantId) {
        return success( orderService.getOrder(id,tenantId));
    }

    @GetMapping("/page")
    @Operation(summary = "获得订单分页")
    @PreAuthorize("@ss.hasPermission('scrm:order:query')")
    public CommonResult<PageResult<OrderDetailPageVO>> getOrderPage(@Valid OrderPageReqVO pageReqVO) {
        //不是超级管理员默认查询自己的数据-是超级管理员直接查询所有的
        Long loginUserId = getLoginUserId();
        if(CollectionUtils.isAnyEmpty(pageReqVO.getUserId()) && !permissionApi.roleIsSuperAdmin(loginUserId).getCheckedData()) {
            pageReqVO.setUserId(Collections.singletonList(Objects.requireNonNull(getLoginUserId()).toString()));
        }
        PageResult<OrderDetailPageVO> pageResult = orderService.getOrderPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出订单 Excel")
    @PreAuthorize("@ss.hasPermission('scrm:order:export')")
    @OperateLog(type = EXPORT)
    public void exportOrderExcel(@Valid OrderPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<OrderDetailPageVO> list = orderService.getOrderPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "订单.xls", "数据", OrderRespVO.class,
                        BeanUtils.toBean(list, OrderRespVO.class));
    }



    @PutMapping("/transfer")
    @Operation(summary = "批量-转移订单-以及关联的客户|回款|发票 的负责人")
    @PreAuthorize("@ss.hasPermission('scrm:order:transfer:owners')")
    public CommonResult<Boolean> transferOrder(@Valid @RequestBody OrderTransfersVo reqVO ,@RequestHeader(value = "Tenant-Id") String tenantId) {
        return success(orderService.transferOrder(reqVO, getLoginUserId(),tenantId));
    }

}